package sell

import (
	"adam2/internal/constants"
	"adam2/internal/model"
	"adam2/internal/util"
	"anubis-framework/pkg/io"
	"gorm.io/gorm"
)

// 优化卖
type OptimizeSell struct {
	db *gorm.DB
}

// 初始化
func (o *OptimizeSell) Init(db *gorm.DB) {
	o.db = db
}

// 执行
func (o *OptimizeSell) DoSell(transactionDate string) {
	io.Infoln("优化卖")

	var quantStockTransactRecordArray *model.QuantStockTransactRecordArray = &model.QuantStockTransactRecordArray{}
	o.db.Raw("select * from quant_stock_transact_record qstr "+
		"where qstr.sell_date=to_date(?, 'yyyy-mm-dd')", transactionDate).Scan(quantStockTransactRecordArray)

	if quantStockTransactRecordArray != nil {
		for _, quantStockTransactRecord := range *quantStockTransactRecordArray {
			// 查询股票
			var stockTransactionDataAll model.StockTransactionDataAll
			o.db.Raw("select * from stock_transaction_data_all t "+
				"where t.code_ = ? and t.date_=to_date(?, 'yyyy-mm-dd')", quantStockTransactRecord.StockCode, transactionDate).Scan(&stockTransactionDataAll)

			// 如果没有查找到记录，可能是因为这个股票在这个交易日停牌，因此跳过这条记录
			if stockTransactionDataAll.ID == 0 {
				o.db.Exec("update optimize_stock_transact_record t set t.fail_sell_reason=? where t.id_=?", constants.SUSPENSION, quantStockTransactRecord.ID)
				io.Infoln("股票[%s]在日期[%s]没有查找到记录，可能是因为这个股票在这个交易日停牌，因此跳过这条记录", quantStockTransactRecord.StockCode, transactionDate)
				continue
			}

			// 如果是一字跌停板，因此跳过这条记录
			if util.OneWordLimitDown(stockTransactionDataAll, transactionDate) {
				o.db.Exec("update optimize_stock_transact_record t set t.fail_sell_reason=? where t.id_=?", constants.LIMIT_DOWN, quantStockTransactRecord.ID)
				io.Infoln("股票[%s]在日期[%s]是一字跌停板，因此跳过这条记录", quantStockTransactRecord.StockCode, transactionDate)
				continue
			}

			o.db.Exec("update optimize_stock_transact_record ostr "+
				"set ostr.sell_date=?, ostr.sell_price=?, ostr.sell_amount=?, "+
				"ostr.profit_and_loss=round(?, 4), ostr.profit_and_loss_rate=?, "+
				"ostr.stamp_duty = ?, ostr.registration_fee_when_sell = ?, ostr.commission_when_sell = ? "+
				"where ostr.account_name=? and ostr.stock_code=? and ostr.buy_date=? "+
				"and ostr.sell_date is null and ostr.sell_price is null and ostr.sell_amount is null",
				quantStockTransactRecord.SellDate, quantStockTransactRecord.SellPrice, quantStockTransactRecord.SellAmount,
				quantStockTransactRecord.ProfitAndLoss, quantStockTransactRecord.ProfitAndLossRate,
				quantStockTransactRecord.StampDuty, quantStockTransactRecord.RegistrationFeeWhenSell, quantStockTransactRecord.CommissionWhenSell,
				quantStockTransactRecord.AccountName, quantStockTransactRecord.StockCode, quantStockTransactRecord.BuyDate)
		}
	}
}
